package com.elitetyc.eliteim.server.handler.impl;

import cn.hutool.json.JSONUtil;
import com.elitetyc.eliteim.common.constant.Constants;
import com.elitetyc.eliteim.common.handler.impl.BaseMsgHandler;
import com.elitetyc.eliteim.common.model.DefaultMsg;
import com.elitetyc.eliteim.common.model.IMUserInfo;
import com.elitetyc.eliteim.common.model.impl.IMUserInfoImpl;
import com.elitetyc.eliteim.common.proto.RequestProto;
import com.elitetyc.eliteim.common.util.MsgUtil;
import com.elitetyc.eliteim.server.holder.SessionSocketHolder;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 获取用户列表
 * @Date 2021/9/17 16:11
 */
@Component
@Slf4j
public class UserListMsgHandlerImpl extends BaseMsgHandler<DefaultMsg> {


    @Override
    public boolean support(int type) {
        return Constants.RequestType.ULIST==type;
    }

    @Override
    public void handleMsg(ChannelHandlerContext ctx, RequestProto.RequestProtocol source, DefaultMsg msg) {
        List<IMUserInfoImpl> imUserInfos = new ArrayList<>();
        for (SessionSocketHolder.ServerChannelUserInfo channelUserInfo : SessionSocketHolder.CHANNEL_USER_INFO_MAP.values()) {
            imUserInfos.add(IMUserInfoImpl.buildUserInfo(channelUserInfo.getUserInfo()));
        }
        final RequestProto.RequestProtocol uLIstMsg = MsgUtil.buildMsg(Constants.RequestType.ULIST, JSONUtil.toJsonStr(imUserInfos));
        ctx.channel().writeAndFlush(uLIstMsg).addListener(future -> {
            log.info("return ulist!");
        });
    }
}
